package org.sbbs.base.searcher.impl;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.sbbs.base.searcher.SearchFilter;
import org.sbbs.base.searcher.SearchRule;

public class JqgridSelfSearchFilter extends SearchFilter {
	private JqgridSelfSearchFilter(String field, String op, String searchFor) {
		this.setMultiSearch(false);
		this.setGroupOp("single");
		SearchRule sr = new SearchRule();
		sr.setData(searchFor);
		sr.setField(field);
		sr.setOp(op);
		this.getRules().add(sr);
	}

	private JqgridSelfSearchFilter(String jqgridfilters) {

		if (jqgridfilters != null && !jqgridfilters.equalsIgnoreCase("")) {
			this.setMultiSearch(true);// = true;
			JSONObject jsonFilter = (JSONObject) JSONSerializer
					.toJSON(jqgridfilters);
			this.setGroupOp(jsonFilter.getString("groupOp"));

			Object rules_string = jsonFilter.get("rules");
			if (rules_string != null) {
				JSONArray jsonRules = (JSONArray) JSONSerializer
						.toJSON(rules_string);

				int rulesCount = JSONArray.getDimensions(jsonRules)[0];
				for (int i = 0; i < rulesCount; i++) {
					JSONObject rule = jsonRules.getJSONObject(i);
					SearchRule srule = new SearchRule();
					srule.setField(rule.getString("field"));
					srule.setOp(rule.getString("op"));
					srule.setData(rule.getString("data"));
					this.getRules().add(srule);
				}
			}

			Object groups_string = jsonFilter.get("groups");
			if (groups_string != null) {
				JSONArray jsonGroups = (JSONArray) JSONSerializer
						.toJSON(groups_string);
				int groupsCount = JSONArray.getDimensions(jsonGroups)[0];
				for (int i = 0; i < groupsCount; i++) {
					JSONObject group = jsonGroups.getJSONObject(i);
					SearchFilter sf = new JqgridSelfSearchFilter(group
							.toString());
					this.getGroups().add(sf);
				}
			}

		}

	}

	public static SearchFilter BuildSearchFilter(HttpServletRequest req) {
		String field = req.getParameter("searchField");
		String oper = req.getParameter("searchOper");
		String data = req.getParameter("searchString");
		String filters = req.getParameter("filters");

		SearchFilter sf = null;
		if (filters != null && !filters.equals("")) {
			sf = new JqgridSelfSearchFilter(filters);
		} else if (field != null && data != null && oper != null) {
			sf = new JqgridSelfSearchFilter(field, oper, data);
		} else {
			sf = null;
		}
		return sf;

	}

}
